package com.itheima.tilas.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itheima.tilas.Utils.JwtUtil;
import com.itheima.tilas.Utils.ResultUtil;
import com.itheima.tilas.entity.Emp;
import com.itheima.tilas.mapper.EmpMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.Interceptor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * 登录拦截器 拦截器由spring提供
 * @author 132
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    EmpMapper empMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("开始执行http请求过滤");
/*        String requestUri = request.getRequestURI();
        if (requestUri.contains("login")) {
            return true;
        }
        可以在config中配置排除*/
        String token = request.getHeader("token");
        if (Objects.isNull(token)) {
            writeErrorResponse(response, "请先登录");
            return false;
        }
        //TODO 使用jwt工具类验证token是否正确
        try {
            JSONObject jsonObject = JwtUtil.verifyToken(token);
            Emp emp = empMapper.selectEmpByUsername(jsonObject.getString("username"));
            if (Objects.isNull(emp) || !emp.getPassword().equals(jsonObject.getString("password"))) {
                writeErrorResponse(response, "Token不合法或者已过期");
                return false;
            }
        } catch (Exception e) {
            writeErrorResponse(response, "Token不合法或者已过期");
            log.info("过滤完成");
            return false;
        }
        return true;
    }
    private static void writeErrorResponse(HttpServletResponse servletResponse, String msg) throws IOException {
        //设置UTF-8编码
        servletResponse.setContentType("application/json; charset=UTF-8");
        servletResponse.setCharacterEncoding("UTF-8");
        //设置状态码
        //import org.apache.http.HttpStatus apache下的包
        //servletResponse.setStatus(HttpStatus.SC_UNAUTHORIZED)
        //import org.springframework.http.HttpStatus springBoot下的状态码包
        servletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        PrintWriter writer = servletResponse.getWriter();
        ResultUtil fail = ResultUtil.fail(msg);
        //使用fastJson 把对象转成json字符串
        writer.write(JSONObject.toJSONString(fail));
    }
}
